  
  
/*  
* Copyright @ 2017 com.iflysse.trains  
* xebest-erp 下午8:59:33  
* All right reserved.  
*  
*/  
  
package com.xebest.web.service.impl;  

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.xebest.common.enums.erp.order.VenOrderStatusEnum;
import com.xebest.common.enums.erp.order.VenOrderSumPurAddTypeEnum;
import com.xebest.common.enums.erp.purch.VenPurchStatusEnum;
import com.xebest.common.enums.erp.purch.VenPurchTypeEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreDeliveryStatusEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreDeliveryTypeEnum;
import com.xebest.common.enums.erp.storehouse.VenStorePrintStatusEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreReceiptStatusEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreReceiptTypeEnum;
import com.xebest.common.enums.erp.sys.VenDelEnum;
import com.xebest.common.enums.erp.sys.VenPrintEnum;
import com.xebest.constant.XeConstans;
import com.xebest.util.seq.StoreHouseSeqUtil;
import com.xebest.web.controller.storehouse.XeVenStoreReceiptController;
import com.xebest.web.form.XeVenPurchForm;
import com.xebest.web.mapper.read.XeVenOrderReadMapper;
import com.xebest.web.mapper.read.XeVenPurchOrderReadMapper;
import com.xebest.web.mapper.read.XeVenStoreReceiptDetailReadMapper;
import com.xebest.web.mapper.read.XeVenStoreReceiptReadMapper;
import com.xebest.web.mapper.write.XeVenOrderWriteMapper;
import com.xebest.web.mapper.write.XeVenPurchOrderDetailWriteMapper;
import com.xebest.web.mapper.write.XeVenStoreDelivDetailWriteMapper;
import com.xebest.web.mapper.write.XeVenStoreDeliveryWriteMapper;
import com.xebest.web.mapper.write.XeVenStoreInventoryWriteMapper;
import com.xebest.web.mapper.write.XeVenStoreReceiptDetailWriteMapper;
import com.xebest.web.mapper.write.XeVenStoreReceiptWriteMapper;
import com.xebest.web.mapper.write.XeVenStoreStockWriteMapper;
import com.xebest.web.model.XeVenOrderInfoDetailEntity;
import com.xebest.web.model.XeVenPurchOrderDetailEntity;
import com.xebest.web.model.XeVenStoreDelivDetailEntity;
import com.xebest.web.model.XeVenStoreDeliveryEntity;
import com.xebest.web.model.XeVenStoreInventoryDetailEntity;
import com.xebest.web.model.XeVenStoreInventoryEntity;
import com.xebest.web.model.XeVenStoreReceiptDetailEntity;
import com.xebest.web.model.XeVenStoreReceiptEntity;
import com.xebest.web.model.XeVenStoreStockEntity;
import com.xebest.web.service.XeVenOrderService;
import com.xebest.web.service.XeVenPurchService;
import com.xebest.web.service.XeVenStoreInventoryService;
import com.xebest.web.service.XeVenStoreReceiptService;
import com.xebest.web.view.XeVenSendView;
import com.xebest.web.view.XeVenStoreReceiptDetailView;
import com.xebest.web.view.XeVenStoreReceiptView;

  

/**
 * 入库单业务类
 * @desc: xebest-erp  
 * @author: 杜春静 
 * @createTime: 2017年6月29日 下午7:14:12  
 * @history:  
 * @version: v1.0
 */
@Service
public class XeVenStoreReceiptServiceImpl implements XeVenStoreReceiptService{
	
	private static final Logger log = LoggerFactory.getLogger(XeVenStoreReceiptController.class);//日志记录类
	
	@Autowired
	XeVenStoreReceiptReadMapper  receiptReadMapper;//入库单读类
	@Autowired
	XeVenStoreInventoryWriteMapper  xeVenStoreInventoryWriteMapper;//库存一览的写Mapper
	
	@Autowired
	XeVenStoreReceiptWriteMapper  receiptWriteMapper;//入库单写类
	@Autowired
	XeVenStoreReceiptDetailReadMapper xeVenStoreReceiptDetailReadMapper;//入库单商品明细读类
	@Autowired
	XeVenStoreReceiptDetailWriteMapper xeVenStoreReceiptDetailWriteMapper;//入库单商品明细写类 
	@Autowired
	XeVenStoreInventoryService xeVenStoreInventoryService;//库存一览业务类
	@Autowired
	XeVenPurchService xeVenPurchService;//采购单业务类
	@Autowired
	XeVenOrderService xeVenOrderService;//订单业务类
	@Autowired
	XeVenStoreStockWriteMapper storeStockWriteMapper;//备货表
	
	@Autowired
	XeVenStoreDeliveryWriteMapper deliveryWriteMapper;//出库单写
	
	@Autowired
	XeVenStoreDelivDetailWriteMapper  delivDetailWriteMapper;//出库商品明细写
	
	@Autowired
	XeVenOrderReadMapper orderReadMapper;//订单mapper读
	
	@Autowired
	XeVenOrderWriteMapper orderWriteMapper;//订单mapper写
	
	@Autowired
	XeVenPurchOrderReadMapper xeVenPurchOrderReadMapper;
	
	@Autowired
	XeVenPurchOrderDetailWriteMapper xeVenPurchOrderDetailWriteMapper;//采购单写mapper
	
	@Override
	public List<XeVenStoreReceiptView> listReceiptByParam(
			Map<String, Object> param) {
		return receiptReadMapper.listStoreReceiptByParam(param);  
	}

	  
	/*  
	 * 添加入库单
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenStoreReceiptService#saveStoreReceipt(com.xebest.web.model.XeVenStoreAllotEntity)  
	*/  
	@Override
	@Transactional(value="writeTransactionManager")
	public int saveStoreReceipt(XeVenStoreReceiptEntity form) throws Exception {
		log.info("普通入库，参数为："+JSONObject.toJSONString(form));
		int result = 0;
		String receiptOrder = "";
		StringBuffer purchZeroFlag = new StringBuffer();//采购是否有0入库
		if(StringUtils.isEmpty(form.getReceiptOrder())){
			receiptOrder = StoreHouseSeqUtil.seqUtils.createReceiptOrder();
			log.info("生成的入库单业务标识为receiptCode：{}", receiptOrder);
			form.setReceiptOrder(receiptOrder);
		} else {
			/*调拨入库时，入库单号在前面生成*/
			receiptOrder = form.getReceiptOrder();
		}
		List<XeVenStoreReceiptDetailEntity> receiptDetailList = form.getReceiptDetailList();
        /*使用迭代器进行边遍历边操作*/
		Iterator<XeVenStoreReceiptDetailEntity> it = receiptDetailList.iterator();
		while(it.hasNext()){
			XeVenStoreReceiptDetailEntity bean = it.next();
			if(StringUtils.isEmpty(bean.getProSku())||bean.getCurrentInNum().equals(BigDecimal.ZERO)){
				purchZeroFlag.append("false,");
				
				it.remove();
			}
			bean.setReceiptOrder(receiptOrder);
			// 设置入库批次
			bean.setBatchNo(StoreHouseSeqUtil.seqUtils.createReceiptBatchNo());
		}
		//如果所有的商品入库量都为零，则不进行入库操作
		if(receiptDetailList != null && receiptDetailList.size() > 0){
		//  1.添加入库单
			result = receiptWriteMapper.insertStoreReceipt(form);

			StringBuffer  purchaseFlag = new StringBuffer();//是否更新采购单状态
			// 2:添加入库单商品明细
			if(result>0){
				xeVenStoreReceiptDetailWriteMapper.batchInsertReceiptDetail(receiptDetailList);
				
				//入库单的商品明细
				for(XeVenStoreReceiptDetailEntity proEntity : receiptDetailList){
					XeVenStoreInventoryEntity storeInvEntity = new XeVenStoreInventoryEntity();
					//封装库存一览主表信息
					storeInvEntity.setStoreId(form.getStoreId());
					storeInvEntity.setUserCode(form.getUserCode());
					storeInvEntity.setProSku(proEntity.getProSku());
					storeInvEntity.setActualInv(proEntity.getCurrentInNum());
					storeInvEntity.setProNum(proEntity.getProNum());
					storeInvEntity.setProMainImg(proEntity.getProMainImg());
					storeInvEntity.setProName(proEntity.getProName());
					storeInvEntity.setProCategoryId(proEntity.getProCategoryId());
					storeInvEntity.setProCategoryName(proEntity.getProCategoryName());
					storeInvEntity.setProPricingType(proEntity.getProPricingType());
					storeInvEntity.setProUnit(proEntity.getProUnit());
					storeInvEntity.setProSpecName(proEntity.getProSpecName());
					storeInvEntity.setProSepcValue(proEntity.getProSepcValue());
					storeInvEntity.setFrozenFlag(proEntity.getFrozenFlag());
					storeInvEntity.setCreateUser(form.getCreateUser());
					storeInvEntity.setModifyUser(form.getModifyUser());
					
					//要添加的库存一览的商品明细
					List<XeVenStoreInventoryDetailEntity> storeInvDetailList = new ArrayList<XeVenStoreInventoryDetailEntity>();
					// 如果入库类型为 采购入库
					if(VenStoreReceiptTypeEnum.CG_RECEIPT.getValue()==form.getReceiptType()){
						BigDecimal transitInv = proEntity.getCurrentInNum().multiply(new BigDecimal(-1));
						storeInvEntity.setTransitInv(transitInv.setScale(2, BigDecimal.ROUND_HALF_UP));
						BigDecimal planInNum = proEntity.getPlanInNum();
						 /**
						  *在当前位置上，本次入库数可以查到
						  */
						 BigDecimal totalReceiptNum = receiptWriteMapper.countReceiptNum(form.getRelationOrder(), proEntity.getProSku());
						 /** 已入库数 已经的提交事务*/
						 BigDecimal arrivalNum = totalReceiptNum.subtract(proEntity.getCurrentInNum());
						 BigDecimal moreProNum = planInNum.subtract(arrivalNum);
						 //统计当前采购单已入库数量
						//如果计划采购数量小于已入库数量，采购单异常完成,在途数为计划购买数-已收货数
						 if(planInNum.compareTo(totalReceiptNum)<0){
							 purchaseFlag.append("Big,");
							 BigDecimal tranInv = moreProNum.multiply(new BigDecimal(-1));
							 storeInvEntity.setTransitInv(tranInv.setScale(2, BigDecimal.ROUND_HALF_UP));
						 }
						//如果计划采购数量等于已入库数量，采购单正常完成
						 if(planInNum.compareTo(totalReceiptNum)==0){
							 purchaseFlag.append("Normal,");
						 }
						 //如果计划采购数量大于已入库数量，采购单为采购中
						 if(planInNum.compareTo(totalReceiptNum)>0){
							 purchaseFlag.append("Small,");
						 }
					}
					//封装库存一览从表
					XeVenStoreInventoryDetailEntity storeInvDetail = new XeVenStoreInventoryDetailEntity();
					storeInvDetail.setProSku(proEntity.getProSku());
					storeInvDetail.setBatchNo(proEntity.getBatchNo());
					storeInvDetail.setBatchPrice(proEntity.getBatchPrice());
					storeInvDetail.setpBatchNo(proEntity.getpBatchNo());
					storeInvDetail.setReceiptOrder(proEntity.getReceiptOrder());
					storeInvDetail.setInsideInv(proEntity.getCurrentInNum());
					storeInvDetail.setActualInv(proEntity.getCurrentInNum());
					storeInvDetail.setCreateUser(form.getCreateUser());
					storeInvDetail.setModifyUser(form.getModifyUser());
					storeInvDetailList.add(storeInvDetail);
					storeInvEntity.setStoreInvDetailList(storeInvDetailList);
					//添加库存一览信息
					result = xeVenStoreInventoryService.saveStoreInv(storeInvEntity);
				}
				
				if(result > 0){

					XeVenPurchForm xeVenPurchForm = new XeVenPurchForm();
					xeVenPurchForm.setPurchType(VenPurchTypeEnum.LARGE_BUY.getValue());
					xeVenPurchForm.setPurchOrder(form.getRelationOrder());
					xeVenPurchForm.setUserCode(form.getUserCode());
					xeVenPurchForm.setVersion(form.getVersion());
					xeVenPurchForm.setModifyUser(form.getModifyUser());
					String  resultPurchFlag = purchaseFlag.toString();
					
					String purchZeroFlagStr = purchZeroFlag.toString();
					log.info("仓库发货，采购单{}的入库情况为{}，采购入库数量是否有入库量为0{}。",form.getRelationOrder(),resultPurchFlag,purchZeroFlagStr);
					//采购单还未完成
					if(resultPurchFlag.contains("Small")){
						
					}else if(resultPurchFlag.contains("Big") && !purchZeroFlagStr.contains("false")){//采购单异常完成
						xeVenPurchForm.setPurchStatus(VenPurchStatusEnum.ABNORMAL_COMPLETE.getValue());
						//更新采购单为异常完成
						xeVenPurchService.updatePurchOrderToFinish(xeVenPurchForm);
					}else if(resultPurchFlag.contains("Normal") && !purchZeroFlagStr.contains("false")){//采购单正常完成
						xeVenPurchForm.setPurchStatus(VenPurchStatusEnum.NORMAL_COMPLETE.getValue());
						xeVenPurchService.updatePurchOrderToFinish(xeVenPurchForm);
					}
					
				}
			}
		}
		
		return result;  
		
	}


	  
	/* 
	 * 查询入库单商品明细 
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenStoreReceiptService#listReceiptDetailByParam(java.util.Map)  
	*/  
	
	@Override
	public List<XeVenStoreReceiptDetailEntity> listReceiptDetailByParam(
			Map<String, Object> param) {
		  
		return xeVenStoreReceiptDetailReadMapper.listReceiptDetailByEntity(param);  
		
	}


	  
	/*  
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenStoreReceiptService#listReceiptDetailView(java.util.Map)  
	*/  
	
	@Override
	public List<XeVenStoreReceiptDetailView> listReceiptDetailView(
			Map<String, Object> param) {
		  
		
		return xeVenStoreReceiptDetailReadMapper.listReceiptDetailView(param);  
		
	}


	  
	/*  
	 * 零采仓自动入库、出库
	 * 零采仓发货，采购单和订单是1:1关系，根据订单查询出对应的采购单，并对零采的采购单进行一次性入库，一次性出库
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenStoreReceiptService#autoReceiptSendZeroStore(com.xebest.web.view.XeVenSendView)  
	*/  
	
	@Override
	@Transactional(value="writeTransactionManager")
	public int autoReceiptSendZeroStore(XeVenSendView orderInfo) throws Exception {
		log.info("零采发货，参数为："+JSONObject.toJSONString(orderInfo));
		int result = 0 ; 
		// 根据订单号查询出采购单商品明细
		Map<String, Object> paramPurchase = new HashMap<String, Object>();
		paramPurchase.put("orderId", orderInfo.getOrderId());
		paramPurchase.put("userCode", orderInfo.getUserCode());
		
		List<XeVenPurchOrderDetailEntity> purchProductList = xeVenPurchOrderDetailWriteMapper.queryPurchProductList(paramPurchase);
		log.info("根据订单号{}查询出采购单商品明细，总条数{}",orderInfo.getOrderId(),purchProductList);
		if(null != purchProductList && purchProductList.size() > 0){
			
			String purchOrder = purchProductList.get(0).getPurchOrder();
			
			// 封装入库单主表
			XeVenStoreReceiptEntity receiptEntity = new XeVenStoreReceiptEntity();
			String receiptOrder = StoreHouseSeqUtil.seqUtils.createReceiptOrder();
			receiptEntity.setReceiptOrder(receiptOrder);
			receiptEntity.setStoreId(orderInfo.getStoreId());
			receiptEntity.setUserCode(orderInfo.getUserCode());
			receiptEntity.setRelationOrder(purchOrder);
			receiptEntity.setStoreName(orderInfo.getStoreHouseName());
			receiptEntity.setReceiptType(VenStoreReceiptTypeEnum.CG_RECEIPT.getValue());
			receiptEntity.setReceiptStatus(VenStoreReceiptStatusEnum.RECEIPT.getValue());
			receiptEntity.setPrintStatus(VenStorePrintStatusEnum.NO.getValue());
			receiptEntity.setCreateUser(orderInfo.getModfiyUser());
			receiptEntity.setModifyUser(orderInfo.getModfiyUser());
			receiptEntity.setDelFlag(VenDelEnum.NO.getValue());
			receiptEntity.setRemark("零采仓采购入库");
			//入库单商品明细
			List<XeVenStoreReceiptDetailEntity> receiptDetailList = new ArrayList<XeVenStoreReceiptDetailEntity>();
			//封装出库单主表
			XeVenStoreDeliveryEntity delivEntity = new XeVenStoreDeliveryEntity();
			String delivOrder = StoreHouseSeqUtil.seqUtils.createDeliveryOrder();
			delivEntity.setDeliveryOrder(delivOrder);
			delivEntity.setUserCode(orderInfo.getUserCode());
			delivEntity.setRelationOrder(orderInfo.getOrderId());
			delivEntity.setStoreId(orderInfo.getStoreId());
			delivEntity.setStoreName(orderInfo.getStoreHouseName());
			delivEntity.setDeliveryType(VenStoreDeliveryTypeEnum.SALES_DELIVERY.getValue());
			delivEntity.setDeliveryStatus(VenStoreDeliveryStatusEnum.DELIVERY.getValue());
			delivEntity.setPrintStatus(VenPrintEnum.NO.getValue());
			delivEntity.setCreateUser(orderInfo.getModfiyUser());
			delivEntity.setModifyUser(orderInfo.getModfiyUser());
			delivEntity.setDelFlag(VenDelEnum.NO.getValue());
			delivEntity.setRemark("零采仓销售出库");
			//出库单商品
			List<XeVenStoreDelivDetailEntity> delivDetailList = new ArrayList<XeVenStoreDelivDetailEntity>();
			
			//备货信息
			List<XeVenStoreStockEntity> storeStockList = new ArrayList<XeVenStoreStockEntity>();
			
			StringBuffer  purchaseFlag = new StringBuffer();//是否更新采购单状态
			// 循环采购单商品明细,封装入库单商品明细
			for(XeVenPurchOrderDetailEntity purchPro : purchProductList){
				
				//本次入库量  根据订单号，sku查询订单的商品实发量
				BigDecimal realSendNum = new BigDecimal(0);
				BigDecimal orderPurNum = new BigDecimal(0);//订单上商品购买的数量
				Map<String, Object> orderDetailParam = new HashMap<String, Object>();
				orderDetailParam.put("orderId", orderInfo.getOrderId());
				orderDetailParam.put("userCode", orderInfo.getUserCode());
				orderDetailParam.put("proSku", purchPro.getProSku());
				List<XeVenOrderInfoDetailEntity> orderDetailList = orderWriteMapper.getOrderDetailByParam(orderDetailParam);
				if(null == orderDetailList || orderDetailList.size() == 0){
					continue;
				}
				 
				if(null != orderDetailList && orderDetailList.size() > 0){
					realSendNum = orderDetailList.get(0).getRealSendNum();
					orderPurNum = orderDetailList.get(0).getPurchaseNum();
					if(new BigDecimal(0).compareTo(realSendNum)==0){
						// 如果实发量为0，订单占用数清空，订单占用数-商品的购买数
						XeVenStoreInventoryEntity invEntity = new XeVenStoreInventoryEntity();
						invEntity.setUserCode(delivEntity.getUserCode());
						invEntity.setStoreId(delivEntity.getStoreId());
						invEntity.setProSku(purchPro.getProSku());
						invEntity.setModifyUser(delivEntity.getModifyUser());
						BigDecimal lockedInv = orderPurNum.multiply(new BigDecimal(-1));
						invEntity.setLockedInv(lockedInv.setScale(2, BigDecimal.ROUND_HALF_UP));
						log.info("零采发货，实发量为0，释放用户{}的订单{}上商品sku{}的订单占用数{}，该商品释放的所在的仓库为{}。",delivEntity.getUserCode(),orderInfo.getOrderId(),
								 purchPro.getProSku(),orderPurNum,delivEntity.getStoreId());
						xeVenStoreInventoryWriteMapper.updateStoreInvByMap(invEntity, null); 
						//设置采购单异常完成
						purchaseFlag.append("Big,");
						continue;
					 }
				}
				
				BigDecimal purchaseNum = purchPro.getProNum();
				//如果实发量等于采购数量，采购单正常完成
				 if(purchaseNum.compareTo(realSendNum)==0){
					 purchaseFlag.append("Normal,");
				 }
				 //如果实发量大于采购数量，采购单为异常完成
				 if(purchaseNum.compareTo(realSendNum) != 0){
					 purchaseFlag.append("Big,");
				 }
				
				XeVenStoreReceiptDetailEntity receiptDetail = new XeVenStoreReceiptDetailEntity();
				receiptDetail.setReceiptOrder(receiptOrder);
				receiptDetail.setProSku(purchPro.getProSku());
				String batchNo = StoreHouseSeqUtil.seqUtils.createReceiptBatchNo();
				receiptDetail.setBatchNo(batchNo);
				receiptDetail.setBatchPrice(purchPro.getBuyPrice());
				receiptDetail.setProMainImg(purchPro.getPicUrl());
				receiptDetail.setProNum(purchPro.getProNo());
				receiptDetail.setProCategoryId(purchPro.getCategoryCode());
				receiptDetail.setProCategoryName(purchPro.getCategoryName());
				receiptDetail.setProName(purchPro.getProName());
				receiptDetail.setProUnit(purchPro.getProUnit());
				receiptDetail.setProSepcValue(purchPro.getSpecValue());
				receiptDetail.setProPricingType(purchPro.getPriceType());
				receiptDetail.setCurrentInNum(realSendNum);
				receiptDetail.setFrozenFlag(purchPro.getFrozenFlag());
				receiptDetail.setCreateUser(orderInfo.getModfiyUser());
				receiptDetail.setModifyUser(orderInfo.getModfiyUser());
				receiptDetailList.add(receiptDetail);
				
				
				//封装库存一览
				XeVenStoreInventoryEntity storeInvEntity = new XeVenStoreInventoryEntity();
				//封装库存一览主表信息
				storeInvEntity.setStoreId(delivEntity.getStoreId());
				storeInvEntity.setUserCode(delivEntity.getUserCode());
				storeInvEntity.setProSku(purchPro.getProSku());
				storeInvEntity.setActualInv(realSendNum);
				storeInvEntity.setProNum(purchPro.getProNo());
				storeInvEntity.setProMainImg(purchPro.getPicUrl());
				storeInvEntity.setProName(purchPro.getProName());
				storeInvEntity.setProCategoryId(purchPro.getCategoryCode());
				storeInvEntity.setProCategoryName(purchPro.getCategoryName());
				storeInvEntity.setProPricingType(purchPro.getPriceType());
				storeInvEntity.setProUnit(purchPro.getProUnit());
				storeInvEntity.setProSepcValue(purchPro.getSpecValue());
				storeInvEntity.setFrozenFlag(purchPro.getFrozenFlag());
				storeInvEntity.setCreateUser(orderInfo.getModfiyUser());
				storeInvEntity.setModifyUser(orderInfo.getModfiyUser());
				
				//要添加的库存一览的商品明细
				List<XeVenStoreInventoryDetailEntity> storeInvDetailList = new ArrayList<XeVenStoreInventoryDetailEntity>();
				//封装库存一览从表
				XeVenStoreInventoryDetailEntity storeInvDetail = new XeVenStoreInventoryDetailEntity();
				storeInvDetail.setProSku(purchPro.getProSku());
				storeInvDetail.setBatchNo(batchNo);
				storeInvDetail.setBatchPrice(purchPro.getBuyPrice());
				storeInvDetail.setReceiptOrder(receiptOrder);
				storeInvDetail.setInsideInv(realSendNum);
				storeInvDetail.setActualInv(realSendNum);
				storeInvDetail.setCreateUser(orderInfo.getModfiyUser());
				storeInvDetail.setModifyUser(orderInfo.getModfiyUser());
				storeInvDetailList.add(storeInvDetail);
				storeInvEntity.setStoreInvDetailList(storeInvDetailList);
				
				//添加库存一览信息
				result = xeVenStoreInventoryService.saveStoreInv(storeInvEntity);
				
				//根据这些信息进行备货
				XeVenStoreStockEntity storeStock = new XeVenStoreStockEntity();
				storeStock.setOrderId(orderInfo.getOrderId());
				storeStock.setProSku(purchPro.getProSku());
				storeStock.setStoreId(orderInfo.getStoreId());
				storeStock.setUserCode(orderInfo.getUserCode());
				storeStock.setCreateUser(orderInfo.getModfiyUser());
				storeStock.setModifyUser(orderInfo.getModfiyUser());
				storeStock.setReceiptBacthNo(receiptOrder);
				storeStock.setReceiptBatchPrice(purchPro.getBuyPrice());
				storeStock.setStockNums(realSendNum);//商品实发量就是商品备货数
				storeStockList.add(storeStock);
				
				//根据采购单商品信息封装出库信息
				XeVenStoreDelivDetailEntity delivDetail = new XeVenStoreDelivDetailEntity();
				delivDetail.setDeliverOrder(delivOrder);
				delivDetail.setProSku(purchPro.getProSku());
				delivDetail.setDelivBatchPrice(purchPro.getBuyPrice());
				delivDetail.setProOutNum(realSendNum);
				delivDetail.setPlanOutNum(orderPurNum);
				delivDetail.setProMainImg(purchPro.getPicUrl());
				delivDetail.setProNum(purchPro.getProNo());
				delivDetail.setProCategoryId(purchPro.getCategoryCode());
				delivDetail.setProCategoryName(purchPro.getCategoryName());
				delivDetail.setProName(purchPro.getProName());
				delivDetail.setProSpecValue(purchPro.getSpecValue());
				delivDetail.setProPricingType(purchPro.getPriceType());
				delivDetail.setProUnit(purchPro.getProUnit());
				delivDetail.setCreateUser(orderInfo.getModfiyUser());
				delivDetail.setModifyUser(orderInfo.getModfiyUser());
				delivDetailList.add(delivDetail);
			}
			/*如果入库单商品不为空*/
			if(receiptDetailList != null && receiptDetailList.size() > 0){
				//  添加入库单
				log.info("零采发货，添加入库单,入库单号为：{}，入库的关联单号为：{}",receiptEntity.getReceiptOrder(),receiptEntity.getRelationOrder());
				result = receiptWriteMapper.insertStoreReceipt(receiptEntity);
				// 添加入库单商品明细
				if(result > 0 ){
					log.info("零采发货，添加入库单明细，明细为{}条",receiptDetailList.size());
					result = xeVenStoreReceiptDetailWriteMapper.batchInsertReceiptDetail(receiptDetailList);
				}
				//入库时实际库存增加
			}
			/*备货的商品信息不为空*/
			if(result > 0 && storeStockList != null && storeStockList.size() > 0){
			//添加备货信息
				result = storeStockWriteMapper.batchInsertStoreStock(storeStockList);
				log.info("零采发货，批量添加备货信息，备货数据总共为{}条，执行结果为{}",storeStockList.size(),result);
			}
			/* 如果出库单的商品信息不为空 */
			if(result>0 && delivDetailList != null && delivDetailList.size() > 0){
				//添加出库单
				log.info("零采发货，添加出库单主表信息，出库单号{}，关联单号{}",delivEntity.getDeliveryOrder(),delivEntity.getRelationOrder());
				result = deliveryWriteMapper.insertStoreDeliv(delivEntity);
				//添加出库单明细
				if(result > 0){
					result = delivDetailWriteMapper.batchInsertDelivDetail(delivDetailList);
					log.info("零采发货，批量添加出库商品明细，数据总共为{}条，执行结果为{}",delivDetailList.size(),result);
				}
				delivEntity.setDelivDtailList(delivDetailList);
				//出库时，更新库存 实际库存减少，释放订单占用
				if(result > 0){
					log.info("零采发货，发货完成后，根据出库信息释放订单占用数");
					result = xeVenStoreInventoryService.updateStoreInvAndDetailByDeliv(delivEntity);
				}
			}
			
			if(result > 0){
				XeVenPurchForm purchForm = new XeVenPurchForm();
				purchForm.setPurchType(VenPurchTypeEnum.RETAIL_BUY.getValue());
				purchForm.setPurchOrder(purchOrder);
				purchForm.setUserCode(orderInfo.getUserCode());
				purchForm.setModifyUser(orderInfo.getModfiyUser());
				String  resultPurchFlag = purchaseFlag.toString();
				log.info("零采发货，采购单{}的入库情况为{}。",purchOrder,resultPurchFlag);
				//采购单还未完成
				if(resultPurchFlag.contains("Big")){
					purchForm.setPurchStatus(VenPurchStatusEnum.ABNORMAL_COMPLETE.getValue());
					xeVenPurchService.finishPurchOrder(purchForm);
				}else if(resultPurchFlag.contains("Normal")){//采购单正常完成
					purchForm.setPurchStatus(VenPurchStatusEnum.NORMAL_COMPLETE.getValue());
					xeVenPurchService.finishPurchOrder(purchForm);
				}
			}
		}
		
		return result;
		
		
	}


	  
	/*  
	 * 整柜仓自动入库、自动出库
	 * 整柜仓发货时，订单：采购单 的对应关系是N:1，单个订单发货，采购单进行一次入库，一次出库。
	 * 如果采购单对应的订单全部发货完成，并且总的商品的收货量等于采购单的商品的采购量，则采购单正常完成；
	 * 如果采购对应的订单全部发货完成，并且总的商品的收货量等小于采购单的商品的采购量，则采购单异常常完成；
	 * 如果采购对应的订单部分发货完成，并且没有待发货状态，并且总的商品的收货量等小于采购单的商品的采购量，则采购单异常常完成；
	 * 如果采购对应的订单部分发货完成，部分待发货，则采购单为采购中
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenStoreReceiptService#autoReceiptSendAllotStore(com.xebest.web.view.XeVenSendView, com.xebest.web.view.ErpUserInfo)  
	*/  
	
	@Override
	public int autoReceiptSendAllotStore(XeVenSendView orderInfo) throws Exception {
		log.info("整柜仓发货，参数为："+JSONObject.toJSONString(orderInfo)); 
		int result = 0 ; 
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderId",orderInfo.getOrderId());
//		params.put("orderStatus",VenOrderStatusEnum.WAIT_SEND.getValue());
		params.put("delFlag",VenDelEnum.NO.getValue());
		//查询订单关联的采购单所关联的所有的订单所关联的采购单
		List<Map<String, Object>> resultList = orderWriteMapper.queryOrderListByParams(params);
		List<String> purchOrders = resultList.stream()
                .map(key -> key.get("purchOrder").toString()).distinct().collect(Collectors.toList());
		//情况一： 对应一个采购单 订单与采购单的关系是1对1或者是n对1
		 if (purchOrders.size() == XeConstans._XE_ONE) {
			 //查询该采购单是否是手动关联的订单
			Boolean isHandRelation =  resultList.stream().filter(key -> key.get("addType").equals(VenOrderSumPurAddTypeEnum.MANUAL.getValue())).count() > 0;
			// 根据订单号查询出采购单商品明细
				Map<String, Object> paramPurchase = new HashMap<String, Object>();
				paramPurchase.put("orderId", orderInfo.getOrderId());
				paramPurchase.put("userCode", orderInfo.getUserCode());
				List<XeVenPurchOrderDetailEntity> purchProductList = xeVenPurchOrderDetailWriteMapper.queryPurchProductList(paramPurchase);
				log.info("根据订单号{}查询出采购单商品明细，总条数{}",orderInfo.getOrderId(),purchProductList);
				if(null != purchProductList && purchProductList.size() > 0){
					String purchOrder = purchProductList.get(0).getPurchOrder();
					// 封装入库单主表
					XeVenStoreReceiptEntity receiptEntity = new XeVenStoreReceiptEntity();
					String receiptOrder = StoreHouseSeqUtil.seqUtils.createReceiptOrder();
					receiptEntity.setReceiptOrder(receiptOrder);
					receiptEntity.setStoreId(orderInfo.getStoreId());
					receiptEntity.setUserCode(orderInfo.getUserCode());
					receiptEntity.setRelationOrder(purchOrder);
					receiptEntity.setStoreName(orderInfo.getStoreHouseName());
					receiptEntity.setReceiptType(VenStoreReceiptTypeEnum.CG_RECEIPT.getValue());
					receiptEntity.setReceiptStatus(VenStoreReceiptStatusEnum.RECEIPT.getValue());
					receiptEntity.setPrintStatus(VenStorePrintStatusEnum.NO.getValue());
					receiptEntity.setCreateUser(orderInfo.getModfiyUser());
					receiptEntity.setModifyUser(orderInfo.getModfiyUser());
					receiptEntity.setDelFlag(VenDelEnum.NO.getValue());
					receiptEntity.setRemark("整柜仓采购入库");
					//入库单商品明细
					List<XeVenStoreReceiptDetailEntity> receiptDetailList = new ArrayList<XeVenStoreReceiptDetailEntity>();
					//封装出库单主表
					XeVenStoreDeliveryEntity delivEntity = new XeVenStoreDeliveryEntity();
					String delivOrder = StoreHouseSeqUtil.seqUtils.createDeliveryOrder();
					delivEntity.setDeliveryOrder(delivOrder);
					delivEntity.setUserCode(orderInfo.getUserCode());
					delivEntity.setRelationOrder(orderInfo.getOrderId());
					delivEntity.setStoreId(orderInfo.getStoreId());
					delivEntity.setStoreName(orderInfo.getStoreHouseName());
					delivEntity.setDeliveryType(VenStoreDeliveryTypeEnum.SALES_DELIVERY.getValue());
					delivEntity.setDeliveryStatus(VenStoreDeliveryStatusEnum.DELIVERY.getValue());
					delivEntity.setPrintStatus(VenPrintEnum.NO.getValue());
					delivEntity.setCreateUser(orderInfo.getModfiyUser());
					delivEntity.setModifyUser(orderInfo.getModfiyUser());
					delivEntity.setDelFlag(VenDelEnum.NO.getValue());
					delivEntity.setRemark("整柜仓销售出库");
					//出库单商品
					List<XeVenStoreDelivDetailEntity> delivDetailList = new ArrayList<XeVenStoreDelivDetailEntity>();
					
					//备货信息
					List<XeVenStoreStockEntity> storeStockList = new ArrayList<XeVenStoreStockEntity>();
					
					StringBuffer  purchaseFlag = new StringBuffer();//是否更新采购单状态
					// 循环采购单商品明细,封装入库单商品明细
					for(XeVenPurchOrderDetailEntity purchPro : purchProductList){
						//本次入库量  根据订单号，sku查询订单的商品实发量
						BigDecimal realSendNum = new BigDecimal(0);
						BigDecimal orderPurNum = new BigDecimal(0);//订单上商品购买的数量
						Map<String, Object> orderDetailParam = new HashMap<String, Object>();
						orderDetailParam.put("orderId", orderInfo.getOrderId());
						orderDetailParam.put("userCode", orderInfo.getUserCode());
						orderDetailParam.put("proSku", purchPro.getProSku());
						
						List<XeVenOrderInfoDetailEntity> orderDetailList = orderWriteMapper.getOrderDetailByParam(orderDetailParam);
						if(null == orderDetailList || orderDetailList.size() == 0){
							continue;
						}
						if(null != orderDetailList && orderDetailList.size() > 0){
							realSendNum = orderDetailList.get(0).getRealSendNum();
							orderPurNum = orderDetailList.get(0).getPurchaseNum();
							if(new BigDecimal(0).compareTo(realSendNum)==0){
								// 如果实发量为0，订单占用数清空，订单占用数-商品的购买数
								XeVenStoreInventoryEntity invEntity = new XeVenStoreInventoryEntity();
								invEntity.setUserCode(delivEntity.getUserCode());
								invEntity.setStoreId(delivEntity.getStoreId());
								invEntity.setProSku(purchPro.getProSku());
								invEntity.setModifyUser(delivEntity.getModifyUser());
								BigDecimal lockedInv = orderPurNum.multiply(new BigDecimal(-1));
								invEntity.setLockedInv(lockedInv.setScale(2, BigDecimal.ROUND_HALF_UP));
								log.info("整柜仓发货，实发量为0，释放用户{}的订单{}上商品sku{}的订单占用数{}，该商品释放的所在的仓库为{}。",delivEntity.getUserCode(),orderInfo.getOrderId(),
										 purchPro.getProSku(),orderPurNum,delivEntity.getStoreId());
								xeVenStoreInventoryWriteMapper.updateStoreInvByMap(invEntity, null);
								//设置采购单异常完成
								purchaseFlag.append("Big,");
								 continue;
							 }
						}
						BigDecimal purchaseNum = purchPro.getProNum();
						//1.1 根据采购单号查询关联订单的状态，判断是否有待发货
						Map<String, Object> orderParam = new HashMap<String, Object>();
						orderParam.put("purchOrder", purchOrder);
						orderParam.put("orderStatus", VenOrderStatusEnum.WAIT_SEND.getValue());
						orderParam.put("delFlag", VenDelEnum.NO.getValue());
						
						List<Map<String, Object>> purOrderList = orderWriteMapper.queryOrderListByParams(orderParam);
						
						/*1.2 如果没有待发货的，根据采购单号查询关联订单的sku的总的收货量，如果总的实发量等于采购单的购买
						    数量，则采购单正常完成，否则异常完成*/
						if(null != purOrderList && purOrderList.size() == 1 ){
							if(purOrderList.get(0).get("orderId").equals(orderInfo.getOrderId())){
								orderParam.put("proSku",purchPro.getProSku());
								
								 BigDecimal sumReceiptNum = receiptWriteMapper.countReceiptNum(purchOrder, purchPro.getProSku());
								//BigDecimal sumRealSendNum = orderReadMapper.sumPurchase(orderParam);
								sumReceiptNum = realSendNum.add(sumReceiptNum);
								
								// 如果总的入库量等于采购数量，采购单正常完成
								 if(purchaseNum.compareTo(sumReceiptNum)==0){
									 purchaseFlag.append("Normal,");
								 }
								 //如果采购数量大于总的入库量，采购单为异常完成
								 if(purchaseNum.compareTo(sumReceiptNum) != 0){
									 purchaseFlag.append("Big,");
								 }
							}
							
						}
						
						
						XeVenStoreReceiptDetailEntity receiptDetail = new XeVenStoreReceiptDetailEntity();
						receiptDetail.setReceiptOrder(receiptOrder);
						receiptDetail.setProSku(purchPro.getProSku());
						String batchNo = StoreHouseSeqUtil.seqUtils.createReceiptBatchNo();
						receiptDetail.setBatchNo(batchNo);
						receiptDetail.setBatchPrice(purchPro.getBuyPrice());
						receiptDetail.setProMainImg(purchPro.getPicUrl());
						receiptDetail.setProNum(purchPro.getProNo());
						receiptDetail.setProCategoryId(purchPro.getCategoryCode());
						receiptDetail.setProCategoryName(purchPro.getCategoryName());
						receiptDetail.setProName(purchPro.getProName());
						receiptDetail.setProUnit(purchPro.getProUnit());
						receiptDetail.setProSepcValue(purchPro.getSpecValue());
						receiptDetail.setProPricingType(purchPro.getPriceType());
						receiptDetail.setCurrentInNum(realSendNum);
						receiptDetail.setCreateUser(orderInfo.getModfiyUser());
						receiptDetail.setModifyUser(orderInfo.getModfiyUser());
						receiptDetailList.add(receiptDetail);
						
						//要添加的库存一览的商品明细
						List<XeVenStoreInventoryDetailEntity> storeInvDetailList = new ArrayList<XeVenStoreInventoryDetailEntity>();
						//封装库存一览
						XeVenStoreInventoryEntity storeInvEntity = new XeVenStoreInventoryEntity();
						//封装库存一览主表信息
						storeInvEntity.setStoreId(delivEntity.getStoreId());
						storeInvEntity.setUserCode(delivEntity.getUserCode());
						storeInvEntity.setProSku(purchPro.getProSku());
						storeInvEntity.setActualInv(realSendNum);
						storeInvEntity.setProNum(purchPro.getProNo());
						storeInvEntity.setProMainImg(purchPro.getPicUrl());
						storeInvEntity.setProName(purchPro.getProName());
						storeInvEntity.setProCategoryId(purchPro.getCategoryCode());
						storeInvEntity.setProCategoryName(purchPro.getCategoryName());
						storeInvEntity.setProPricingType(purchPro.getPriceType());
						storeInvEntity.setProUnit(purchPro.getProUnit());
						storeInvEntity.setProSepcValue(purchPro.getSpecValue());
						storeInvEntity.setFrozenFlag(purchPro.getFrozenFlag());
						storeInvEntity.setCreateUser(orderInfo.getModfiyUser());
						storeInvEntity.setModifyUser(orderInfo.getModfiyUser());
						
						
						//封装库存一览从表
						XeVenStoreInventoryDetailEntity storeInvDetail = new XeVenStoreInventoryDetailEntity();
						storeInvDetail.setProSku(purchPro.getProSku());
						storeInvDetail.setBatchNo(batchNo);
						storeInvDetail.setBatchPrice(purchPro.getBuyPrice());
						storeInvDetail.setReceiptOrder(receiptOrder);
						storeInvDetail.setInsideInv(realSendNum);
						storeInvDetail.setActualInv(realSendNum);
						storeInvDetail.setCreateUser(orderInfo.getModfiyUser());
						storeInvDetail.setModifyUser(orderInfo.getModfiyUser());
						storeInvDetailList.add(storeInvDetail);
						storeInvEntity.setStoreInvDetailList(storeInvDetailList);
						
						//添加库存一览信息
						result = xeVenStoreInventoryService.saveStoreInv(storeInvEntity);
						
						//根据这些信息进行备货
						XeVenStoreStockEntity storeStock = new XeVenStoreStockEntity();
						storeStock.setOrderId(orderInfo.getOrderId());
						storeStock.setProSku(purchPro.getProSku());
						storeStock.setStoreId(orderInfo.getStoreId());
						storeStock.setUserCode(orderInfo.getUserCode());
						storeStock.setCreateUser(orderInfo.getModfiyUser());
						storeStock.setModifyUser(orderInfo.getModfiyUser());
						storeStock.setReceiptBacthNo(receiptOrder);
						storeStock.setReceiptBatchPrice(purchPro.getBuyPrice());
						storeStock.setStockNums(realSendNum);//商品实发量就是商品备货数
						storeStockList.add(storeStock);
						
						//根据采购单商品信息封装出库信息
						XeVenStoreDelivDetailEntity delivDetail = new XeVenStoreDelivDetailEntity();
						delivDetail.setDeliverOrder(delivOrder);
						delivDetail.setProSku(purchPro.getProSku());
						delivDetail.setDelivBatchPrice(purchPro.getBuyPrice());
						delivDetail.setProOutNum(realSendNum);
						delivDetail.setPlanOutNum(orderPurNum);
						delivDetail.setProMainImg(purchPro.getPicUrl());
						delivDetail.setProNum(purchPro.getProNo());
						delivDetail.setProCategoryId(purchPro.getCategoryCode());
						delivDetail.setProCategoryName(purchPro.getCategoryName());
						delivDetail.setProName(purchPro.getProName());
						delivDetail.setProSpecValue(purchPro.getSpecValue());
						delivDetail.setProPricingType(purchPro.getPriceType());
						delivDetail.setProUnit(purchPro.getProUnit());
						delivDetail.setCreateUser(orderInfo.getModfiyUser());
						delivDetail.setModifyUser(orderInfo.getModfiyUser());
						delivDetailList.add(delivDetail);
					}
					
					/*如果入库单商品不为空*/
					if(receiptDetailList != null && receiptDetailList.size() > 0){
						//  添加入库单
					//  添加入库单
						log.info("整柜仓发货，添加入库单,入库单号为：{}，入库的关联单号为：{}",receiptEntity.getReceiptOrder(),receiptEntity.getRelationOrder());
						result = receiptWriteMapper.insertStoreReceipt(receiptEntity);
						// 添加入库单商品明细
						if(result > 0 ){ 
							log.info("整柜仓发货，添加入库单明细，明细为{}条",receiptDetailList.size());
							result = xeVenStoreReceiptDetailWriteMapper.batchInsertReceiptDetail(receiptDetailList);
						}
					}
					/*备货的商品信息不为空*/
					if(result > 0 && storeStockList != null && storeStockList.size() > 0){
						//添加备货信息
						result = storeStockWriteMapper.batchInsertStoreStock(storeStockList);
						log.info("整柜仓发货，批量添加备货信息，备货数据总共为{}条，执行结果为{}",storeStockList.size(),result);
					}
					/* 如果出库单的商品信息不为空 */
					if(result>0 && delivDetailList != null && delivDetailList.size() > 0){
						//添加出库单
						log.info("整柜仓发货，添加出库单主表信息，出库单号{}，关联单号{}",delivEntity.getDeliveryOrder(),delivEntity.getRelationOrder());
						result = deliveryWriteMapper.insertStoreDeliv(delivEntity);
						//添加出库单明细
						if(result>0){
							result = delivDetailWriteMapper.batchInsertDelivDetail(delivDetailList);
							log.info("整柜仓发货，批量添加出库商品明细，数据总共为{}条，执行结果为{}",delivDetailList.size(),result);
						}
						delivEntity.setDelivDtailList(delivDetailList);
						//出库时，更新库存 实际库存建设，释放订单占用
						if(result > 0){
							log.info("整柜仓发货，发货完成后，根据出库信息释放订单占用数");
							result = xeVenStoreInventoryService.updateStoreInvAndDetailByDeliv(delivEntity);
						}
					}
					
					if(result > 0){
						//TODO  如果订单是自动采购，进行采购单的自动完成
						if(!isHandRelation){
							
							XeVenPurchForm purchForm = new XeVenPurchForm();
							purchForm.setPurchType(VenPurchTypeEnum.ALLOT_BUY.getValue());
							purchForm.setPurchOrder(purchOrder);
							purchForm.setUserCode(orderInfo.getUserCode());
							purchForm.setModifyUser(orderInfo.getModfiyUser());
							String  resultPurchFlag = purchaseFlag.toString();
							log.info("整柜仓发货，采购单{}的入库情况为{}。",purchOrder,resultPurchFlag);
							//采购单还未完成
							if(resultPurchFlag.contains("Big")){
								purchForm.setPurchStatus(VenPurchStatusEnum.ABNORMAL_COMPLETE.getValue());
								xeVenPurchService.finishPurchOrder(purchForm);
							}else if(resultPurchFlag.contains("Normal")){//采购单正常完成
								purchForm.setPurchStatus(VenPurchStatusEnum.NORMAL_COMPLETE.getValue());
								xeVenPurchService.finishPurchOrder(purchForm);
							}
						}
						
					}
				}
         }else {//1.2 对应多个采购单,订单与采购单关系是1对n或n对n  这两种情况都是手动关联的采购单和订单，不需要进行采购单的自动完成操作
        	 List<XeVenOrderInfoDetailEntity> orderDetailList = orderInfo.getOrderDetailList();
        	 if(orderDetailList != null && orderDetailList.size() > 0){
        		 
        			//封装出库单主表 
 				XeVenStoreDeliveryEntity delivEntity = new XeVenStoreDeliveryEntity();
 				String delivOrder = StoreHouseSeqUtil.seqUtils.createDeliveryOrder();
 				delivEntity.setDeliveryOrder(delivOrder); 
 				delivEntity.setUserCode(orderInfo.getUserCode());
 				delivEntity.setRelationOrder(orderInfo.getOrderId());
 				delivEntity.setStoreId(orderInfo.getStoreId());
 				delivEntity.setStoreName(orderInfo.getStoreHouseName());
 				delivEntity.setDeliveryType(VenStoreDeliveryTypeEnum.SALES_DELIVERY.getValue());
 				delivEntity.setDeliveryStatus(VenStoreDeliveryStatusEnum.DELIVERY.getValue());
 				delivEntity.setPrintStatus(VenPrintEnum.NO.getValue());
 				delivEntity.setCreateUser(orderInfo.getModfiyUser());
 				delivEntity.setModifyUser(orderInfo.getModfiyUser());
 				delivEntity.setDelFlag(VenDelEnum.NO.getValue());
 				delivEntity.setRemark("整柜仓销售出库");
  				
 				//出库单商品
  				List<XeVenStoreDelivDetailEntity> delivDetailList = new ArrayList<XeVenStoreDelivDetailEntity>();
        		 
        		 //查询订单关联的采购单明细
        		 Map<String, Object> orderMap = new HashMap<String, Object>();
        		 orderMap.put("orderId", orderInfo.getOrderId());
        		 List<XeVenPurchOrderDetailEntity> purchProductList = this.xeVenPurchOrderDetailWriteMapper.queryPurchProductList(orderMap);
        		 String oldPurchOrder = "";
        		 XeVenStoreReceiptEntity receiptEntity = new XeVenStoreReceiptEntity();//入库单主表
        		 List<XeVenStoreReceiptDetailEntity> receiptDetailList = new ArrayList<XeVenStoreReceiptDetailEntity>();//入库单明细
        		 String receiptOrder = "";//入库单号
        		 BigDecimal realSendNum;
        		 BigDecimal orderPurNum;
        		//用于判断采购单发货后，采购单的完成情况 包含purchOrder,proSku,realNum,proNum,modifyUser,userCode
// 				List<Map<String, Object>> purchSendData = new ArrayList<Map<String, Object>>();
  				List<XeVenStoreStockEntity> storeStockList = new ArrayList<XeVenStoreStockEntity>();//备货信息
  					
  				for(XeVenPurchOrderDetailEntity orderPurchDetail : purchProductList){
  				
        			 String nowPurchOrder = orderPurchDetail.getPurchOrder();
        			//如果采购单
  					realSendNum = orderPurchDetail.getRealSendNum();
  					orderPurNum = orderPurchDetail.getProNum();
  					if(realSendNum == null){
  						realSendNum = new BigDecimal(0);
  					}
  					if(orderPurNum == null){
  						orderPurNum = new BigDecimal(0);
  					}
  					/*屏蔽掉采购单的采购情况
  					 * if(realSendNum == null){//如果获取的实发数量为 null 说明采购单上这个商品没有进行销售
  					//构造采购单发货状况
  						Map<String, Object> purchSendMap = new HashMap<String, Object>();
  						purchSendMap.put("purchOrder", nowPurchOrder);
  						purchSendMap.put("sendStatus", "Big");
  						purchSendData.add(purchSendMap);
  						continue;
  					}*/
  					if(new BigDecimal(0).compareTo(realSendNum)==0){ 
  						// 如果实发量为0，订单占用数清空，订单占用数-商品的购买数
  						XeVenStoreInventoryEntity invEntity = new XeVenStoreInventoryEntity();
  						invEntity.setUserCode(orderInfo.getUserCode());
  						invEntity.setStoreId(orderInfo.getStoreId());
  						invEntity.setProSku(orderPurchDetail.getProSku());
  						invEntity.setModifyUser(orderInfo.getModfiyUser());
  						BigDecimal lockedInv = orderPurNum.multiply(new BigDecimal(-1));
  						invEntity.setLockedInv(lockedInv.setScale(2, BigDecimal.ROUND_HALF_UP));
  						log.info("整柜(整柜)仓发货，实发量为0，释放用户{}的订单{}上商品sku{}的订单占用数{}，该商品释放的所在的仓库为{}。",orderInfo.getUserCode(),orderInfo.getOrderId(),
  								orderPurchDetail.getProSku(),orderPurNum,orderInfo.getStoreId());
  						xeVenStoreInventoryWriteMapper.updateStoreInvByMap(invEntity, null);
  						
  						/*//构造采购单发货状况
  						Map<String, Object> purchSendMap = new HashMap<String, Object>();
  						purchSendMap.put("purchOrder", nowPurchOrder);
  						purchSendMap.put("sendStatus", "Big");
  						purchSendData.add(purchSendMap);*/
  						 continue;
  					 } 
  					if(StringUtils.isEmpty(oldPurchOrder)){
  						oldPurchOrder = nowPurchOrder;
	  					// 封装入库单主表
	  					receiptEntity = new XeVenStoreReceiptEntity();
	  					receiptOrder = StoreHouseSeqUtil.seqUtils.createReceiptOrder();
	  					receiptEntity.setReceiptOrder(receiptOrder);
	  					receiptEntity.setStoreId(orderInfo.getStoreId());
	  					receiptEntity.setUserCode(orderInfo.getUserCode());
	  					receiptEntity.setRelationOrder(nowPurchOrder);
	  					receiptEntity.setStoreName(orderInfo.getStoreHouseName());
	  					receiptEntity.setReceiptType(VenStoreReceiptTypeEnum.CG_RECEIPT.getValue());
	  					receiptEntity.setReceiptStatus(VenStoreReceiptStatusEnum.RECEIPT.getValue());
	  					receiptEntity.setPrintStatus(VenStorePrintStatusEnum.NO.getValue());
	  					receiptEntity.setCreateUser(orderInfo.getModfiyUser());
	  					receiptEntity.setModifyUser(orderInfo.getModfiyUser());
	  					receiptEntity.setDelFlag(VenDelEnum.NO.getValue());
	  					receiptEntity.setRemark("整柜仓采购入库");
  					}
        			 if(!oldPurchOrder.equals(nowPurchOrder)){
        				 /*如果入库单商品不为空*/
      					if(receiptDetailList != null && receiptDetailList.size() > 0){
      						//  添加入库单
      					//  添加入库单
      						log.info("整柜(整柜)仓发货，添加入库单,入库单号为：{}，入库的关联单号为：{}",receiptEntity.getReceiptOrder(),receiptEntity.getRelationOrder());
      						result = receiptWriteMapper.insertStoreReceipt(receiptEntity);
      						// 添加入库单商品明细
      						if(result > 0 ){ 
      							log.info("整柜(整柜)仓发货，添加入库单明细，明细为{}条",receiptDetailList.size());
      							result = xeVenStoreReceiptDetailWriteMapper.batchInsertReceiptDetail(receiptDetailList);
      						}
      					}
        				 
        				// 封装入库单主表
      					receiptEntity = new XeVenStoreReceiptEntity();
      					receiptOrder = StoreHouseSeqUtil.seqUtils.createReceiptOrder();
      					receiptEntity.setReceiptOrder(receiptOrder);
      					receiptEntity.setStoreId(orderInfo.getStoreId());
      					receiptEntity.setUserCode(orderInfo.getUserCode());
      					receiptEntity.setRelationOrder(nowPurchOrder);
      					receiptEntity.setStoreName(orderInfo.getStoreHouseName());
      					receiptEntity.setReceiptType(VenStoreReceiptTypeEnum.CG_RECEIPT.getValue());
      					receiptEntity.setReceiptStatus(VenStoreReceiptStatusEnum.RECEIPT.getValue());
      					receiptEntity.setPrintStatus(VenStorePrintStatusEnum.NO.getValue());
      					receiptEntity.setCreateUser(orderInfo.getModfiyUser());
      					receiptEntity.setModifyUser(orderInfo.getModfiyUser());
      					receiptEntity.setDelFlag(VenDelEnum.NO.getValue());
      					receiptEntity.setRemark("整柜仓采购入库");
      					//入库单商品明细
     					receiptDetailList = new ArrayList<XeVenStoreReceiptDetailEntity>();
     					oldPurchOrder = nowPurchOrder;
        			 }
        			 //入库单明细
        			 XeVenStoreReceiptDetailEntity receiptDetail = new XeVenStoreReceiptDetailEntity();
						receiptDetail.setReceiptOrder(receiptOrder);
						receiptDetail.setProSku(orderPurchDetail.getProSku());
						String batchNo = StoreHouseSeqUtil.seqUtils.createReceiptBatchNo();
						receiptDetail.setBatchNo(batchNo);
						receiptDetail.setBatchPrice(orderPurchDetail.getBuyPrice());
						receiptDetail.setProMainImg(orderPurchDetail.getPicUrl());
						receiptDetail.setProNum(orderPurchDetail.getProNo());
						receiptDetail.setProCategoryId(orderPurchDetail.getCategoryCode());
						receiptDetail.setProCategoryName(orderPurchDetail.getCategoryName());
						receiptDetail.setProName(orderPurchDetail.getProName());
						receiptDetail.setProUnit(orderPurchDetail.getProUnit());
						receiptDetail.setProSepcValue(orderPurchDetail.getSpecValue());
						receiptDetail.setProPricingType(orderPurchDetail.getPriceType());
						receiptDetail.setCurrentInNum(orderPurchDetail.getRealSendNum());
						receiptDetail.setCreateUser(orderInfo.getModfiyUser());
						receiptDetail.setModifyUser(orderInfo.getModfiyUser());
						receiptDetailList.add(receiptDetail);
						//要添加的库存一览的商品明细
 						List<XeVenStoreInventoryDetailEntity> storeInvDetailList = new ArrayList<XeVenStoreInventoryDetailEntity>();
 						//封装库存一览
 						XeVenStoreInventoryEntity storeInvEntity = new XeVenStoreInventoryEntity();
 						//封装库存一览主表信息
 						storeInvEntity.setStoreId(orderInfo.getStoreId());
 						storeInvEntity.setUserCode(orderInfo.getUserCode());
 						storeInvEntity.setProSku(orderPurchDetail.getProSku());
 						storeInvEntity.setActualInv(orderPurchDetail.getRealSendNum());
 						storeInvEntity.setProNum(orderPurchDetail.getProNo());
 						storeInvEntity.setProMainImg(orderPurchDetail.getPicUrl());
 						storeInvEntity.setProName(orderPurchDetail.getProName());
 						storeInvEntity.setProCategoryId(orderPurchDetail.getCategoryCode());
 						storeInvEntity.setProCategoryName(orderPurchDetail.getCategoryName());
 						storeInvEntity.setProPricingType(orderPurchDetail.getPriceType());
 						storeInvEntity.setProUnit(orderPurchDetail.getProUnit());
 						storeInvEntity.setProSepcValue(orderPurchDetail.getSpecValue());
 						storeInvEntity.setFrozenFlag(orderPurchDetail.getFrozenFlag());
 						storeInvEntity.setCreateUser(orderInfo.getModfiyUser());
 						storeInvEntity.setModifyUser(orderInfo.getModfiyUser());
 						
 						
 						//封装库存一览从表
 						XeVenStoreInventoryDetailEntity storeInvDetail = new XeVenStoreInventoryDetailEntity();
 						storeInvDetail.setProSku(orderPurchDetail.getProSku());
 						storeInvDetail.setBatchNo(batchNo);
 						storeInvDetail.setBatchPrice(orderPurchDetail.getBuyPrice());
 						storeInvDetail.setReceiptOrder(receiptOrder);
 						storeInvDetail.setInsideInv(orderPurchDetail.getRealSendNum());
 						storeInvDetail.setActualInv(orderPurchDetail.getRealSendNum());
 						storeInvDetail.setCreateUser(orderInfo.getModfiyUser());
 						storeInvDetail.setModifyUser(orderInfo.getModfiyUser());
 						storeInvDetailList.add(storeInvDetail);
 						storeInvEntity.setStoreInvDetailList(storeInvDetailList);
 						
 						//添加库存一览信息
 						result = xeVenStoreInventoryService.saveStoreInv(storeInvEntity);
 						
 						//根据这些信息进行备货
 						XeVenStoreStockEntity storeStock = new XeVenStoreStockEntity();
 						storeStock.setOrderId(orderInfo.getOrderId());
 						storeStock.setProSku(orderPurchDetail.getProSku());
 						storeStock.setStoreId(orderInfo.getStoreId());
 						storeStock.setUserCode(orderInfo.getUserCode());
 						storeStock.setCreateUser(orderInfo.getModfiyUser());
 						storeStock.setModifyUser(orderInfo.getModfiyUser());
 						storeStock.setReceiptBacthNo(receiptOrder);
 						storeStock.setReceiptBatchPrice(orderPurchDetail.getBuyPrice());
 						storeStock.setStockNums(orderPurchDetail.getRealSendNum());//商品实发量就是商品备货数
 						storeStockList.add(storeStock);
 						/*String purchaseFlag = "";
 						Map<String, Object> purchSendMap = new HashMap<String, Object>();
 					// 如果总的入库量等于采购数量，采购单正常完成
						 if(orderPurNum.compareTo(realSendNum) == 0){
							 purchaseFlag = "Normal";
						 }
						 //如果采购数量大于总的入库量，采购单为异常完成
						 if(orderPurNum.compareTo(realSendNum) != 0){
							 purchaseFlag="Big";
						 }
 						purchSendMap.put("sendStatus", purchaseFlag);
 						purchSendData.add(purchSendMap);*/
 						
 						//根据采购单商品信息封装出库信息
 						XeVenStoreDelivDetailEntity delivDetail = new XeVenStoreDelivDetailEntity();
 						delivDetail.setDeliverOrder(delivOrder);
 						delivDetail.setProSku(orderPurchDetail.getProSku());
 						delivDetail.setDelivBatchPrice(orderPurchDetail.getBuyPrice());
 						delivDetail.setProOutNum(realSendNum);
 						delivDetail.setPlanOutNum(orderPurNum);
 						delivDetail.setProMainImg(orderPurchDetail.getPicUrl());
 						delivDetail.setProNum(orderPurchDetail.getProNo());
 						delivDetail.setProCategoryId(orderPurchDetail.getCategoryCode());
 						delivDetail.setProCategoryName(orderPurchDetail.getCategoryName());
 						delivDetail.setProName(orderPurchDetail.getProName());
 						delivDetail.setProSpecValue(orderPurchDetail.getSpecValue());
 						delivDetail.setProPricingType(orderPurchDetail.getPriceType());
 						delivDetail.setProUnit(orderPurchDetail.getProUnit());
 						delivDetail.setCreateUser(orderInfo.getModfiyUser());
 						delivDetail.setModifyUser(orderInfo.getModfiyUser());
 						delivDetailList.add(delivDetail);
        			 
        		 }
  				if(!StringUtils.isEmpty(receiptEntity) ){
  					/*如果入库单商品不为空*/
					if(receiptDetailList != null && receiptDetailList.size() > 0){
						//  添加入库单
					//  添加入库单
						log.info("整柜(整柜)仓发货，添加入库单,入库单号为：{}，入库的关联单号为：{}",receiptEntity.getReceiptOrder(),receiptEntity.getRelationOrder());
						result = receiptWriteMapper.insertStoreReceipt(receiptEntity);
						// 添加入库单商品明细
						if(result > 0 ){ 
							log.info("整柜(整柜)仓发货，添加入库单明细，明细为{}条",receiptDetailList.size());
							result = xeVenStoreReceiptDetailWriteMapper.batchInsertReceiptDetail(receiptDetailList);
						}
					}
  				}
        		 
        		 /*备货的商品信息不为空*/
					if(result > 0 && storeStockList != null && storeStockList.size() > 0){
						//添加备货信息
						result = storeStockWriteMapper.batchInsertStoreStock(storeStockList);
						log.info("整柜仓发货，批量添加备货信息，备货数据总共为{}条，执行结果为{}",storeStockList.size(),result);
					}
					/* 如果出库单的商品信息不为空 */
					if(result>0 && delivDetailList != null && delivDetailList.size() > 0){
						//添加出库单
						log.info("整柜仓发货，添加出库单主表信息，出库单号{}，关联单号{}",delivEntity.getDeliveryOrder(),delivEntity.getRelationOrder());
						result = deliveryWriteMapper.insertStoreDeliv(delivEntity);
						//添加出库单明细
						if(result>0){
							result = delivDetailWriteMapper.batchInsertDelivDetail(delivDetailList);
							log.info("整柜仓发货，批量添加出库商品明细，数据总共为{}条，执行结果为{}",delivDetailList.size(),result);
						}
						delivEntity.setDelivDtailList(delivDetailList);
						//出库时，更新库存 实际库存建设，释放订单占用
						if(result > 0){
							log.info("整柜仓发货，发货完成后，根据出库信息释放订单占用数");
							result = xeVenStoreInventoryService.updateStoreInvAndDetailByDeliv(delivEntity);
						}
					}
					 
					//1.2.1根据采购单查询是否关联其他代发货的订 单，如果没有，则比较采购单的入库信息
					/*if(purchOrders != null && purchOrders.size() >0){
						for(String purchOrder : purchOrders){
							Map<String, List<Map<String, Object>>> purchOrderGroups = 	purchSendData
		                             .stream().collect(Collectors.groupingBy(key -> key.get("purchOrder").toString()));
		        			 
		        			 Map<String, Object> paramMap = new HashMap<String, Object>();
		            		 paramMap.put("userCode", orderInfo.getUserCode());
		            		 paramMap.put("purchOrder",purchOrder);
		            		 XeVenPurchForm purchForm = new XeVenPurchForm();
	 						purchForm.setPurchType(VenPurchTypeEnum.ALLOT_BUY.getValue());
	 						purchForm.setPurchOrder(purchOrder);
	 						purchForm.setUserCode(orderInfo.getUserCode());
	 						purchForm.setModifyUser(orderInfo.getModfiyUser());

		 						boolean  purchFlag = purchOrderGroups.get(purchOrder).stream().anyMatch(map->"Big".equals(map.get("sendStatus")));
		 						log.info("整柜仓发货，采购单{}是否异常完成{}。",purchOrder,purchFlag);
		 						if(purchFlag){
		 							purchForm.setPurchStatus(VenPurchStatusEnum.ABNORMAL_COMPLETE.getValue());
		 							xeVenPurchService.finishPurchOrder(purchForm);
		 						}else {//采购单正常完成
		 							purchForm.setPurchStatus(VenPurchStatusEnum.NORMAL_COMPLETE.getValue());
		 							xeVenPurchService.finishPurchOrder(purchForm);
		 						}
		 						
						}
						
					}*/
        	 
        	 }
     		
         }
		
		return result;  
		
	}
	public static void main(String[] args) {
		String oldP = "";
		String[] arrayRefVar = {"np1","np1","np2","np3"};
		int r = 0;
		for(int i = 0; i < arrayRefVar.length; i++){
			String newP = arrayRefVar[i];
			
			if(StringUtils.isEmpty(oldP)){
				oldP = newP;
				r++;
			}
			
			if(!oldP.equals(newP)){
				System.out.println(oldP +"不相同"+newP);
				oldP = newP;
				r++;
			}
		}
		System.out.println(r);
	}
	
}
  
